<template>
  <div class="chat-container">

    <!-- 添加折叠按钮 -->
    <div 
      class="collapse-button" 
      @click="toggleConversationList"
      :class="{ collapsed: isConversationListCollapsed }"
    >
      <i :class="isConversationListCollapsed ? 'el-icon-s-unfold' : 'el-icon-s-fold'"></i>
    </div>
    <!-- 会话列表 -->
    <el-aside  class="conversation-list" 
      :width="isConversationListCollapsed ? '0' : '260px'"
      :class="{ collapsed: isConversationListCollapsed }">
      <div class="conversation-header">
        <h3>会话列表</h3>
        <el-button 
          class="new-conversation-btn" 
          type="primary"
          @click="createNewConversation"
          icon="el-icon-plus"
        >
          新建会话
        </el-button>
      </div>
      <el-scrollbar class="conversation-items">
        <div 
          v-for="conversation in conversations" 
          :key="conversation.id"
          @click="selectConversation(conversation.id)"
          :class="['conversation-item', { active: activeConversationId === conversation.id }]"
        >
          <div class="conversation-info">
            <i class="el-icon-chat-line-round"></i>
            <span class="conversation-name">{{ conversation.name || '新会话' }}</span>
          </div>
          <el-button 
            class="delete-btn" 
            type="text" 
            icon="el-icon-close" 
            @click.stop="deleteConversation(conversation.id)"
          />
        </div>
      </el-scrollbar>
    </el-aside>

    <!-- 聊天区域 -->
    <el-main class="chat-area">
      <div class="chat-header" v-if="activeConversationId">
        <h3>{{ activeConversation?.name || '当前会话' }}</h3>
        <el-button 
          size="small" 
          type="text" 
          @click="showRenameDialog = true;newConversationName = activeConversation?.name"
          class="rename-btn"
        >
          <i class="el-icon-edit"></i> 重命名
        </el-button>
      </div>
      
      <el-scrollbar ref="scrollbar" class="messages-box">
        <div class="message-list">
          <div v-for="(message, index) in messages" :key="index" class="message-item">
            <div class="user-message">
              <div class="message-bubble user-bubble">
                {{ message.query }}
              </div>
              <div class="avatar user-avatar">
                <img src="~@/assets/image/person.png" width="40x">
              </div>
              
            </div>
            
            <div class="ai-message">
              <div class="avatar ai-avatar">
                 <img src="~@/assets/image/report.png" width="40x">
              </div>
              <div class="message-bubble ai-bubble">
                <!-- 加载状态 -->
                <div v-if="message.isStreaming && !message.answer" class="loading-indicator">
                  <i class="el-icon-loading"></i> 思考中...
                </div>
                
                <!-- 流式消息 -->
                <div v-if="message.isStreaming" class="streaming-message">
                   <formatted-content :content="message.answer"/>
                </div>
                
                <!-- 完整消息 -->
                 
                <div v-else>
                  <div v-if="hasThinkContent(message.answer)" class="think-content">
                    <div class="think-header" @click="message.isThinkCollapsed = !message.isThinkCollapsed">
                      <i :class="['el-icon-reading', { 'think-expanded': !message.isThinkCollapsed }]"></i>
                      <span>思考过程</span>
                      <i :class="['el-icon-arrow-down', { 'rotate': !message.isThinkCollapsed }]"></i>
                    </div>
                     <pre v-show="!message.isThinkCollapsed">{{ extractThinkContent(message.answer) }}</pre>
                  </div>
                  <formatted-content 
                    :content="isHtmlContent(message.answer) 
                      ? extractMainContent(message.answer) 
                      : message.answer"
                  ></formatted-content>
                </div>
              </div>
            </div>

            <!-- 文件预览 -->
            <div v-if="message.files" class="message-files">
              <div v-for="(file, fIndex) in message.files" :key="fIndex" class="file-preview-item">
                <img v-if="file.type === 'image'" :src="file.url" class="file-preview">
                <el-link v-else :href="file.url" target="_blank" class="file-download">
                  <i class="el-icon-document"></i> 下载文件
                </el-link>
              </div>
            </div>
            <!-- 建议问题展示区域 - 新增部分 -->
          <div 
            v-show="message.suggestedQuestions &&  message.suggestedQuestions.length" 
            class="suggested-questions"
          >
            <div class="suggested-label">推荐问题：</div>
            <div class="suggested-buttons">
              <el-button
                v-for="(question, qIndex) in message.suggestedQuestions"
                :key="qIndex"
                size="mini"
                @click="handleSuggestedQuestion(question)"
                class="suggested-btn"
              >
                {{ question }}
              </el-button>
            </div>
          </div>
          </div>
        </div>
      </el-scrollbar>
      
      <div class="input-area">
        <div class="input-controls">
        <!-- 文件上传 -->
        <div class="file-upload">
          <el-upload
            action="#"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handleFileUpload"
          >
            <el-button 
              class="upload-btn" 
              type="text" 
              icon="el-icon-paperclip"
            />
          </el-upload>
          <div class="file-tags" v-if="uploadedFiles.length > 0">
            <el-tag 
              v-for="(file, index) in uploadedFiles" 
              :key="index" 
              class="file-tag"
              closable
              @close="removeFile(index)">
              {{ file.name || '文件' + (index + 1) }}
            </el-tag>
          </div>
        </div>
          
          <!-- 查询类型选择 -->
          <div class="query-type-selector">
           
            <el-radio-group v-model="queryType" size="small">
              <el-radio 
                v-for="type in queryTypes"
                :key="type.value" 
                :label="type.value"
                border
              >
                {{ type.label }}
              </el-radio>
            </el-radio-group>
          </div>
          
          <!-- 调查数据选择 -->
          <div class="unitselect" v-if="useData">
            <el-checkbox v-model="checked">调查数据</el-checkbox>
            <!-- <el-select v-if="checked" v-model="bigCategoryId" size="small" class="work-select" @change="categorySelectHandler">
                <el-option 
                  v-for="item in bigCategoryList" 
                  :key="item.id" 
                  :label="item.name"
                  :value="item.id"
              />   
            </el-select> -->

            <el-select 
              v-if="checked" 
              v-model="workId" 
              size="small" 
              @change="workSelectHandler"
              placeholder="请选择调查任务"
              class="work-select"
            >
              <el-option 
                v-for="item in workList" 
                :key="item.id" 
                :label="item.name"
                :value="item.id"
              />    
            </el-select>
          </div>
        </div>
        
       <div class="input-container">
          <el-input
            v-model="userInput"
            type="textarea"
            :rows="2"  
            placeholder="输入消息..."
            resize="none"
            @keyup.enter.ctrl.prevent="sendMessage"
            class="message-input"  
          ></el-input>
          <div class="input-actions">
            <el-button 
              type="primary" 
              @click="sendMessage"
              :disabled="!userInput.trim()"
              class="send-btn"
              :loading="isSending"
            >
              <i class="el-icon-s-promotion"></i> 
              发送
            </el-button>
            <el-button 
              v-if="currentTaskId" 
              @click="stopResponse"
              class="stop-btn"
              plain
            >
              <i class="el-icon-switch-button"></i> 停止
            </el-button>
          </div>
        </div>
      </div>
    </el-main>

     <!-- 重命名会话弹窗 -->
    <el-dialog
      title="重命名会话"
      :visible.sync="showRenameDialog"
      width="400px"
      center
      class="rename-dialog"
    >
      <div class="dialog-content">
        <el-input 
          v-model="newConversationName" 
          placeholder="请输入新的会话名称"
          size="medium"
          clearable
        ></el-input>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showRenameDialog = false">取消</el-button>
        <el-button type="primary" @click="renameConversation">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script lang="ts">
import { Component, Vue ,Prop,Watch} from 'vue-property-decorator';
import { difyApi } from '@/api/difyApi';
import { SendMessageParams } from '@/api/difyApi';
import FormattedContent from '@/components/Chat/FormattedContent.vue';
import {findData} from '@/api/dataSearch';
import {historyList} from '@/api/investWork';
import {Getter} from 'vuex-class';
import MarkdownRenderer  from './MarkdownRenderer.vue';
import {getBigCategory} from '@/api/investCategory';
import store from '@/store';
interface ProcessedData {
    dataDetailsVoList: {
        categoryName: string;
        structureName: string;
        title: string[];
        data: any[][];
    }[];
    dictionary: string[];
}

interface ChatMessage {
  id?: string;
  query: string;
  answer: string;
  isStreaming: boolean;
  taskId?: string;
  messageId?: string;
  files?: Array<{
    type: string;
    url: string;
  }>;
  feedback?: 'like' | 'dislike';
  createdAt?: number;
  suggestedQuestions?:any;
  isThinkCollapsed?:any;
}
@Component({
  components: { FormattedContent ,MarkdownRenderer}
})
export default class ChatInterface extends Vue {
  // 状态数据
  userInput = '';
  checked = false;
  workId = '';
  @Getter userInfo:any;
  bigCategoryId = [];
  @Getter departInfo:any;
  queryType = '数据分析'; // 默认查询类型
  @Prop({ default: () => [
    { value: '数据分析', label: '数据分析' },
    { value: '灾情分析', label: '灾情分析' },
    { value: 'Q&A', label: '知识库' }] })
  queryTypes;
  workCodeMap:any = {};
 @Prop({default:() =>true})useData;

  bigCategoryList:any =[];

  activeConversationId: string | null = null;
  activeConversation: any | null = null;
  conversations: any[] = [];
  messages: Array<ChatMessage> = [];
  currentTaskId: string | null = null;
  uploadedFiles: any[] = [];
  workList: any[] = [];
  workData:any =null;
  suggestedQuestions:any = [];
  showRenameDialog = false;
  isConversationListCollapsed = false;
  newConversationName = '';
  messageAccumulators: Record<string, string> = {};
  taskMessages: Record<string, ChatMessage> = {};
  currentPendingMessage: ChatMessage | null = null;
  isSending = false;
  // 生命周期钩子
  async mounted() {
    await this.loadConversations();
    if (this.conversations.length > 0) {
      this.selectConversation(this.conversations[0].id);
    } else {
      this.createNewConversation();
    }
    this.getWorkLit();
    getBigCategory().then((res:any)=>{
      this.bigCategoryList = res.data;
    });
  }

  // 加载会话列表
  async loadConversations() {
    try {
      const response = await difyApi.getConversations(this.userInfo.id); // 替换为实际用户ID
      this.conversations = response.data.data;
    } catch (error) {
      console.error('Failed to load conversations:', error);
    }
  }

   hasThinkContent(content: string): boolean {

    return /<think>[\s\S]*<\/think>/i.test(content);
  }

  // 添加折叠/展开方法
  toggleConversationList() {
    this.isConversationListCollapsed = !this.isConversationListCollapsed;
  }
   // 新增方法：提取主内容（去除think标签）
  extractMainContent(content: string): string {
    const data =  content.replace(/<think>[\s\S]*<\/think>/i, '').trim();

    return data;
  }
  
  // 处理建议问题点击
  handleSuggestedQuestion(question: string) {
    this.userInput = question;
    this.$nextTick(() => {
      // 自动滚动到输入框
      const inputArea = document.querySelector('.input-area');
      if (inputArea) {
        inputArea.scrollIntoView({ behavior: 'smooth', block: 'end' });
      }
    });
    this.sendMessage();
  }
  // 新增方法：检查是否为HTML内容
  isHtmlContent(content: string): boolean {
    return /<\/?[a-z][\s\S]*>/i.test(content);
  }

   // 新增方法：提取think标签内容
  extractThinkContent(content: string): string {
    const match = content.match(/<think>([\s\S]*)<\/think>/i);
    return match ? match[1].trim() : '';
  }

   

  // 创建新会话
  createNewConversation() {
    this.activeConversationId = null;
    this.messages = [];
    this.userInput = '';
  }

   workSelectHandler(val){
    if(this.workId){
      findData({workId:this.workId}).then(res =>{
        this.workData = res.data;

    });
    }else{
      this.workData = null;
    }
  }

  categorySelectHandler(val){
    this.bigCategoryId = val;
    this.workId = '';
  }
  @Watch('queryTypes', { immediate: true })
  changeQeuryTypes(val){
    this.queryType = val[0].value;
  }

  // 选择会话
  async selectConversation(conversationId: string) {
    this.activeConversationId = conversationId;

    this.activeConversation = this.conversations.find(c => c.id === conversationId);
    
    try {
      const response = await difyApi.getMessages(conversationId, this.userInfo.id);
      this.messages = response.data.data.map((msg: any) => ({
        query: msg.query,
        answer: msg.answer,
        isStreaming: false,
        id:msg.id,
        isThinkCollapsed:true,
      }));

      // 加载最后一条消息的建议问题（如果API没有返回）
      if (this.messages.length > 0) {
        const lastMessage = this.messages[this.messages.length - 1];
   
        if (lastMessage.id) {
          await this.loadSuggestedQuestions(lastMessage);
          this.$set(this.messages, this.messages.length - 1, lastMessage);
        }

      }
      

      this.$nextTick(() => {
        this.scrollToBottom();
      });
    } catch (error) {
      console.error('Failed to load messages:', error);
    }
  }

  
  removeFile(index: number) {
    this.uploadedFiles.splice(index, 1);
  }

  // 删除会话
  async deleteConversation(conversationId: string) {
    try {
      // 调用difyApi的deleteConversation方法删除指定会话
      await difyApi.deleteConversation(conversationId, this.userInfo.id);
      // 从会话列表中移除被删除的会话
      this.conversations = this.conversations.filter(c => c.id !== conversationId);
      // 如果当前激活的会话是被删除的会话，则创建一个新的会话
      if (this.activeConversationId === conversationId) {
        this.createNewConversation();
      }
    } catch (error) {
      // 如果删除会话失败，输出错误信息
      console.error('Failed to delete conversation:', error);
    }
  }

   // 添加滚动到底部方法
 scrollToBottom() {
   this.$nextTick(() => {
    const scrollbar = this.$refs.scrollbar as any;
    if (scrollbar && scrollbar.wrap) {
      scrollbar.wrap.scrollTop = scrollbar.wrap.scrollHeight;
    }
  });
}

async loadSuggestedQuestions(message:any) {
  try {
    const response = await difyApi.getSuggestedQuestions(
      message.id, 
      this.userInfo.id
    );
     if (response.data && response.data.data && response.data.data.length > 0) {
      message.suggestedQuestions = response.data.data;
    } else {
      // 如果没有数据，清除建议问题
      message.suggestedQuestions = null;
    }
     this.$nextTick(() => {
      this.scrollToBottom();
      });
  } catch (error) {
    console.error('获取建议问题失败:', error);
    message.suggestedQuestions = null;
  }
}

// 在消息组件中添加反馈按钮
async handleFeedback(messageId: string, rating: 'like' | 'dislike') {
  try {
    await difyApi.sendFeedback(
      messageId, 
      rating, 
      this.userInfo.id,
      '用户反馈'
    );
    this.$message.success('反馈提交成功');
  } catch (error) {
    this.$message.error('反馈提交失败');
  }
}

  // 处理文件上传
  async handleFileUpload(event: Event) {
    const input = event.target as HTMLInputElement;
    if (!input.files || input.files.length === 0) return;

    const file = input.files[0];
    try {
      const response = await difyApi.uploadFile(file, this.userInfo.id);
      this.uploadedFiles.push(response.data);
      console.log('File uploaded:', response.data);
    } catch (error) {
      console.error('File upload failed:', error);
    }
  }

  getWorkLit(){
    historyList().then(res =>{
      if(res && res.data){
          this.workList = res.data;
          this.workList.forEach((w:any) =>{
          this.workCodeMap[w.id] = w.code;
        })
      }
    }).catch(e =>{
      console.error(e);
    });
  }


 

 processData(originalData: any): ProcessedData {
    const dictionary: string[] = [];
    const stringToIndex = new Map<string, number>();
    
    // 递归处理所有数据
    function processValue(value: any): any {
        if (Array.isArray(value)) {
            return value.map(processValue);
        } else if (value !== null && typeof value === 'object') {
            const processedObj: any = {};
            for (const key in value) {
                processedObj[key] = processValue(value[key]);
            }
            return processedObj;
        } else if (typeof value === 'string') {
            if (!stringToIndex.has(value)) {
                stringToIndex.set(value, dictionary.length);
                dictionary.push(value);
            }
            return stringToIndex.get(value);
        }
        return value;
    }

    const processed = processValue(originalData) as ProcessedData;
    processed.dictionary = dictionary;
    return processed;
}
  // 发送消息
  async sendMessage() {
    if (!this.userInput.trim()) return;

    // 添加用户消息到列表
    const userMessage = this.userInput;
    const newMessage = {
      id: `msg-${Date.now()}`,
      query: userMessage,
      answer: '',
      isStreaming: true,
      taskId: '', 
      files: [],
      isThinkCollapsed:true,
    };
    this.messages.push(newMessage);
    this.currentPendingMessage = newMessage; 
    // 保存当前消息索引
    // 准备API参数
    const params: SendMessageParams = {
      inputs: { query_type: this.queryType, auth: store.getters.token},
      query: userMessage,
      response_mode: 'streaming',
      user: this.userInfo.id,
      conversation_id: this.activeConversationId || undefined,
      files: this.uploadedFiles.map(file => ({
        type: file.mime_type.split('/')[0],
        transfer_method: 'local_file',
        upload_file_id: file.id
      }))
    };

    if(this.workData){
     // console.log('workData:',this.processData(this.workData));
      params.inputs['work_data'] = JSON.stringify(this.workData);
      this.checked = false;
    }else{
      params.inputs['work_data'] = '[]';
    }
  // 清空输入和上传文件
    this.userInput = '';
    this.uploadedFiles = [];
    try {

      await difyApi.sendStreamMessage(params, (event) => {

      switch (event.event)  {
      case 'workflow_started':
        this.handleWorkflowStarted(event);
        break;
        
      case 'node_started':
        console.log('Node  started:', event.data.data.node_id); 
        break;
        
      case 'node_finished':
        console.log('Node  finished:', event.data.data.node_id); 
        break;
        
      case 'workflow_finished':
        this.currentTaskId  = null;
        break;
      case 'message':
        this.handleMessageEvent(event);
        break;
      case 'message_end':
        this.handleMessageEndEvent(event);
        break;
      case 'tts_message':
        console.log('TTS  message received:', event.data.message_id); 
        if (event.data.audio) {
          const audio = new Audio(`data:audio/mp3;base64,${event.data.audio}`);
          audio.play();
        }
        //this.playAudio(event.data.url);
        break;
      case 'tts_message_end':
        console.log('TTS  message ended:', event.data.message_id); 
        break;
      case 'error':
        this.handleErrorEvent(event);
        break;
      case 'message_file':
            this.handleMessageFileEvent(event);
          break;
          case 'message_replace':
            this.handleMessageReplaceEvent(event);
             break;
          }
              // 处理用户消息的
    });
    } catch (error) {
      newMessage.answer = `请求失败: ${(error as Error).message}`;
      newMessage.isStreaming = false;
      this.currentTaskId = null;
    }
  }

   // 工作流开始事件处理
  handleWorkflowStarted(event: any) {
    this.currentTaskId = event.data.task_id;
    if (this.currentPendingMessage) {
      this.currentPendingMessage.taskId = event.data.task_id;
      this.taskMessages[event.data.task_id] = this.currentPendingMessage;
      this.currentPendingMessage = null;
    }
  }

   // 消息事件处理
  handleMessageEvent(event: any) {
    const taskId = event.data.task_id;
    if (!taskId || !this.taskMessages[taskId]) return;
    
    const messageId = event.data.message_id;
     this.isSending = true;
    if (!this.messageAccumulators[messageId]) {
      this.messageAccumulators[messageId] = '';
    }
    
    this.messageAccumulators[messageId] = event.data.answer;
    this.taskMessages[taskId].answer = this.messageAccumulators[messageId];
    
    const index = this.messages.findIndex(m => m.id === messageId);
    if (index !== -1) {
      this.$set(this.messages, index, { ...this.taskMessages[taskId] });
    }
    
    this.scrollToBottom();
  }


   handleMessageEndEvent(event: any) {
    const endTaskId = event.data.task_id;
    if (endTaskId && this.taskMessages[endTaskId]) {
      const message = this.taskMessages[endTaskId];
      message.isStreaming = false;
      message.messageId = event.data.message_id;
      delete this.taskMessages[endTaskId];
      
      this.loadSuggestedQuestions(message);
      
      if (!this.activeConversationId) {
        this.activeConversationId = event.data.conversation_id;
        this.loadConversations();
      }
      
      this.isSending = false;
    }
    this.currentTaskId = null;
  }

   // 错误事件处理
  handleErrorEvent(event: any) {
    if (this.currentPendingMessage) {
      this.currentPendingMessage.answer = `错误: ${event.data.message}`;
      this.currentPendingMessage.isStreaming = false;
    }
    this.currentTaskId = null;
    this.isSending = false;
  }
  // 消息替换事件处理
  handleMessageReplaceEvent(event: any) {
    const replaceTaskId = event.data.task_id;
    if (replaceTaskId && this.taskMessages[replaceTaskId]) {
      this.taskMessages[replaceTaskId].answer = event.data.answer;
      this.messageAccumulators[event.data.message_id] = event.data.answer;
      this.scrollToBottom();
    }
  }


   // 消息文件事件处理
  handleMessageFileEvent(event: any) {
    if (event.data.belongs_to === 'assistant') {
      const msgIndex = this.messages.findIndex(m => 
        m.messageId === event.data.conversation_id
      );
      
      if (msgIndex !== -1) {
        const message = { ...this.messages[msgIndex] };
        if (!message.files) message.files = [];
        
        message.files.push({
          type: event.data.type,
          url: event.data.url
        });
        
        this.$set(this.messages, msgIndex, message);
      }
    }
  }

  async renameConversation() {
    
   if (!this.activeConversationId || !this.newConversationName.trim()) return;
    
    try {
      await difyApi.renameConversation(
        this.activeConversationId,
        this.newConversationName,
        this.userInfo.id
      );
      await this.loadConversations();
      this.showRenameDialog = false;
      this.$message.success('会话重命名成功');
    } catch (error) {
      this.$message.error('会话重命名失败');
    }
}
playAudio(url: string) {
  const audio = new Audio(url);
  audio.play().catch(e => console.error('音频播放失败:', e));
}
  // 停止响应
  async stopResponse() {
    if (this.currentTaskId) {
      try {
        await difyApi.stopResponse(this.currentTaskId, this.userInfo.id);
        const lastMessage = this.messages[this.messages.length - 1];
        if (lastMessage.isStreaming) {
          lastMessage.isStreaming = false;
        }
        this.currentTaskId = null;
      } catch (error) {
        console.error('Failed to stop response:', error);
      }
    }
  }
}
</script>
<style scoped lang="scss">
/* ===== 全局样式 ===== */
.chat-container {
  display: flex;
  height: 100vh;
  width: 100%;
  background-color: #f8fafc;
  font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
  overflow: hidden;
}

/* ===== 会话列表样式 ===== */
.conversation-list {
  width: 260px;
  background-color: #ffffff;
  border-right: 1px solid #e6e9ed;
  display: flex;
  flex-direction: column;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  z-index: 10;
  
  .conversation-header {
    padding: 16px;
    padding-left: 60px;
    border-bottom: 1px solid #e6e9ed;
    background-color: #f8fafc;
    display: flex;
    flex-direction: column;
    gap: 12px;
    
    h3 {
      margin: 0;
      text-align: center;
      font-size: 16px;
      color: #2c3e50;
      font-weight: 600;
    }
    
    .new-conversation-btn {
      padding: 10px 16px;
      background: linear-gradient(135deg, #409eff, #66b1ff);
      color: white;
      border: none;
      border-radius: 8px;
      cursor: pointer;
      font-size: 14px;
      display: flex;
      align-items: center;
      justify-content: center;
      transition: all 0.3s;
      box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
      
      i {
        margin-right: 8px;
      }
      
      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
      }
    }
  }
  
  .conversation-items {
    flex: 1;
    overflow-y: auto;
    padding: 12px;
    scrollbar-width: thin;
    scrollbar-color: #d9d9d9 transparent;
    
    &::-webkit-scrollbar {
      width: 6px;
    }
    
    &::-webkit-scrollbar-thumb {
      background-color: #d9d9d9;
      border-radius: 3px;
    }
  }
  
  .conversation-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 16px;
    border-radius: 10px;
    margin-bottom: 10px;
    cursor: pointer;
    transition: all 0.3s;
    background-color: #ffffff;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
    
    &:hover {
      background-color: #f5f7fa;
      transform: translateX(3px);
      
      .delete-btn {
        opacity: 1;
        transform: scale(1);
      }
    }
    
    &.active {
      background-color: #ecf5ff;
      border-left: 3px solid #409eff;
      box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
      
      .conversation-info {
        .conversation-name {
          color: #409eff;
          font-weight: 500;
        }
        
        i {
          color: #409eff;
        }
      }
    }
    
    .conversation-info {
      display: flex;
      align-items: center;
      flex: 1;
      min-width: 0;
      
      i {
        color: #909399;
        margin-right: 12px;
        font-size: 18px;
        flex-shrink: 0;
      }
      
      .conversation-name {
        font-size: 14px;
        color: #606266;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        transition: color 0.3s;
      }
    }
    
    .delete-btn {
      background: none;
      border: none;
      color: #c0c4cc;
      cursor: pointer;
      padding: 4px;
      font-size: 12px;
      opacity: 0;
      transform: scale(0.8);
      transition: all 0.3s;
      display: flex;
      align-items: center;
      justify-content: center;
      width: 24px;
      height: 24px;
      border-radius: 50%;
      
      &:hover {
        background-color: #fef0f0;
        color: #f56c6c;
      }
    }
  }
}

/* ===== 聊天区域样式 ===== */
.chat-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #f0f2f5;
  position: relative;
  min-height: 0;
  padding: 0;
  
  .chat-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12px 20px;
    background-color: #ffffff;
    border-bottom: 1px solid #e6e9ed;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.03);
    z-index: 1;
    
    h3 {
      margin: 0;
      font-size: 16px;
      color: #303133;
      font-weight: 500;
      display: flex;
      align-items: center;
      
      &::before {
        content: "";
        display: inline-block;
        width: 4px;
        height: 16px;
        background-color: #409eff;
        border-radius: 2px;
        margin-right: 10px;
      }
    }
    
    .rename-btn {
      color: #909399;
      transition: color 0.3s;
      
      &:hover {
        color: #409eff;
      }
    }
  }
  
  .messages-box {
    flex: 1;
    padding: 10px 20px 0px 20px;
    overflow-y: auto;
    scroll-behavior: smooth;
    min-height: 0;
    
    .message-list {
      display: flex;
      flex-direction: column;
      gap: 24px;
      //max-width: 900px;
      margin: 0 auto;
      width: 100%;
    }
  }
  
  .message-item {
    display: flex;
    flex-direction: column;
    gap: 20px;
  }
  
  .user-message, .ai-message {
    display: flex;
    width: 100%;
    
    /* 确保头像容器正确显示 */
    .avatar {
      width: 42px;
      height: 42px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-shrink: 0;
      margin-top: 5px;
      font-size: 20px;
      box-shadow: 0 4px 10px rgba(0, 0, 0, 0.08);
      transition: all 0.3s;
      
      /* 确保图标居中 */
      i {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 100%;
        height: 100%;
      }
    }
    
    .user-avatar {
      background: linear-gradient(135deg, #409eff, #66b1ff);
      color: white;
      float:right;
    }
    
    .ai-avatar {
      background: linear-gradient(135deg, #67c23a, #85ce61);
      color: white;
    }
    
    .message-bubble {
      padding: 15px 20px;
      border-radius: 20px;
      line-height: 1.6;
      width:100%;
      font-size: 15px;
      max-width: calc(100% - 60px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.06);
      position: relative;
      margin: 0 10px;
      word-break: break-word;
      white-space: pre-wrap;
      transition: all 0.3s;
    }
    
    .user-bubble {
      background: linear-gradient(135deg, #409eff, #66b1ff);
      color: white;
      border-bottom-right-radius: 6px;
    }
    
    .ai-bubble {
      background-color: #ffffff;
      color: #303133;
      border-bottom-left-radius: 6px;
      box-shadow: 0 4px 14px rgba(0, 0, 0, 0.06);
    }
  }
  
  .user-message {
    justify-content: flex-end;
    
    .message-bubble {
      margin-right: 15px;
    }
    
    .user-bubble {
      &::after {
        content: "";
        position: absolute;
        right: -8px;
        top: 14px;
        width: 0;
        height: 0;
        border-top: 8px solid transparent;
        border-bottom: 8px solid transparent;
        border-left: 8px solid #409eff;
      }
    }
  }
  
  .ai-message {
    justify-content: flex-start;
    
    .message-bubble {
      margin-left: 15px;
    }
    
    .ai-bubble {
      &::before {
        content: "";
        position: absolute;
        left: -8px;
        top: 14px;
        width: 0;
        height: 0;
        border-top: 8px solid transparent;
        border-bottom: 8px solid transparent;
        border-right: 8px solid #ffffff;
      }
    }
  }
  
  /* 思考内容样式 */
  .think-content {
    background-color: #f5f7fa;
    border-left: 4px solid #909399;
    padding: 12px 16px;
    margin: 15px 0;
    border-radius: 0 8px 8px 0;
    font-style: italic;
    color: #606266;
    
    i {
      margin-right: 8px;
      color: #409eff;
    }
    
    pre {
      white-space: pre-wrap;
      font-family: inherit;
      margin: 8px 0 0 0;
      padding: 0;
      font-size: 13px;
      line-height: 1.5;
    }
  }
  
  .streaming-message {
    min-height: 24px;
    display: inline-flex;
    align-items: center;
    
    .cursor {
      display: inline-block;
      width: 8px;
      height: 18px;
      background-color: #606266;
      margin-left: 6px;
      vertical-align: middle;
      border-radius: 2px;
      animation: blink 1s infinite;
    }
  }
  
  @keyframes blink {
    0%, 100% { opacity: 1; }
    50% { opacity: 0.4; }
  }
  
  .message-files {
    margin-top: 8px;
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
    
    .file-preview-item {
      .file-preview {
        max-width: 200px;
        max-height: 150px;
        border-radius: 8px;
        border: 1px solid #e6e9ed;
        transition: all 0.3s;
        
        &:hover {
          transform: scale(1.02);
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }
      }
      
      .file-download {
        display: flex;
        align-items: center;
        color: #409eff;
        text-decoration: none;
        font-size: 14px;
        padding: 6px 12px;
        background-color: #ecf5ff;
        border-radius: 6px;
        transition: all 0.3s;
        
        i {
          margin-right: 6px;
        }
        
        &:hover {
          background-color: #d9ecff;
          transform: translateY(-2px);
        }
      }
    }
  }
  
  /* 建议问题样式 */
  .suggested-questions {
    margin-top: 15px;
    padding-left: 60px;
    margin-bottom: 20px;
    .suggested-label {
      font-size: 13px;
      color: #909399;
      margin-bottom: 8px;
    }
    
    .suggested-buttons {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
    }
    
    .suggested-btn {
      font-size: 12px !important;
      padding: 6px 12px !important;
      border-radius: 15px !important;
      background-color: #f0f7ff !important;
      color: #409eff !important;
      border: 1px solid #d9ecff !important;
      transition: all 0.3s !important;
      
      &:hover {
        background-color: #ecf5ff !important;
        transform: translateY(-2px);
        box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
      }
    }
  }
}

/* ===== 输入区域样式 ===== */
.input-area {
  padding: 12px 20px;
  background-color: #ffffff;
  border-top: 1px solid #e6e9ed;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.03);
  flex-shrink: 0;
  
  .input-controls {
    display: flex;
    flex-wrap: wrap;
    gap: 16px;
    margin-bottom: 10px;
    
    .file-upload {
      display: flex;
      align-items: center;
      gap: 12px;
      
      .upload-btn {
        width: 42px;
        height: 42px;
        border-radius: 50%;
        background-color: #f8fafc;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        color: #606266;
        font-size: 20px;
        transition: all 0.3s;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
        
        &:hover {
          background-color: #ecf5ff;
          color: #409eff;
          transform: translateY(-2px);
        }
      }
      
      .file-tags {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
      }
      
      .file-tag {
        background-color: #ecf5ff;
        color: #409eff;
        padding: 8px 12px;
        border-radius: 8px;
        font-size: 13px;
        display: flex;
        align-items: center;
        box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
        transition: all 0.3s;
        
        i {
          margin-left: 8px;
          cursor: pointer;
          font-size: 12px;
          transition: all 0.2s;
          
          &:hover {
            color: #f56c6c;
            transform: scale(1.2);
          }
        }
      }
    }
    
    .query-type-selector {
      display: flex;
      align-items: center;
      font-size: 14px;
      color: #606266;
      
      label {
        margin-right: 8px;
        white-space: nowrap;
      }
      
      .el-select {
        width: 140px;
      }
    }
    
    .unitselect {
      display: flex;
      align-items: center;
      gap: 10px;
      font-size: 14px;
      color: #606266;
      
      .work-select {
        padding: 8px 12px;
        border: 1px solid #dcdfe6;
        border-radius: 6px;
        font-size: 14px;
        background-color: #f5f7fa;
        transition: all 0.3s;
        min-width: 160px;
        
        &:focus {
          border-color: #409eff;
          box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
        }
      }
    }
  }
  
  .input-container {
    position: relative;
    
    .el-textarea {
      ::v-deep .el-textarea__inner {
        border-radius: 14px;
        padding: 16px;
        border: 1px solid #e6e9ed;
        transition: all 0.3s;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.04);
        font-size: 15px;
        line-height: 1.6;
        
        &:focus {
          border-color: #409eff;
          box-shadow: 0 2px 12px rgba(64, 158, 255, 0.2);
        }
      }
    }
    
    .input-actions {
      position: absolute;
      right: 8px;
      bottom: 8px;
      display: flex;
      gap: 8px;
      z-index: 10;
    }
    
    .send-btn {
      background: linear-gradient(135deg, #409eff, #66b1ff);
      border: none;
      color: white;
      padding: 8px 15px;
      border-radius: 8px;
      font-size: 13px;
      transition: all 0.3s;
      box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
      display: flex;
      align-items: center;
      
      i {
        margin-right: 8px;
      }
      
      &:hover:not(:disabled) {
        transform: translateY(-2px);
        box-shadow: 0 6px 16px rgba(64, 158, 255, 0.3);
      }
      
      &:active:not(:disabled) {
        transform: translateY(0);
      }
      
      &:disabled {
        background: #c0c4cc;
        box-shadow: none;
        transform: none;
        cursor: not-allowed;
      }
    }
    
    .stop-btn {
      background: transparent;
      border: 1px solid #f56c6c;
      color: #f56c6c;
      padding: 8px 15px;
      border-radius: 8px;
      font-size: 13px;
      transition: all 0.3s;
      display: flex;
      align-items: center;
      
      i {
        margin-right: 8px;
      }
      
      &:hover {
        background-color: #fef0f0;
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(245, 108, 108, 0.1);
      }
      
      &:active {
        transform: translateY(0);
      }
    }
  }
}

/* ===== 折叠按钮样式 ===== */
.collapse-button {
  position: absolute;
  top: 16px;
  left: 16px;
  z-index: 100;
  width: 36px;
  height: 36px;
  background-color: #fff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.collapse-button:hover {
  background-color: #f5f7fa;
  transform: scale(1.05);
}

.collapse-button.collapsed {
  left: 16px;
}

.collapse-button i {
  font-size: 18px;
  color: #606266;
  transition: transform 0.3s ease;
}

/* ===== 会话列表折叠动画 ===== */
.conversation-list.collapsed {
  width: 0 !important;
  opacity: 0;
  transform: translateX(-100%);
  pointer-events: none;
}

/* 调整聊天区域宽度 */
.chat-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #f0f2f5;
  position: relative;
  min-height: 0;
  padding: 0;
}

.conversation-list:not(.collapsed) + .chat-area {
  width: calc(100% - 260px);
}

.conversation-list.collapsed + .chat-area {
  width: 100%;
}

/* ===== 思考内容样式 ===== */
.think-header {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 6px 0;
  color: #606266;
  user-select: none;
}

.think-header span {
  margin: 0 8px;
  font-size: 14px;
}

.think-header .el-icon-arrow-down {
  transition: transform 0.3s;
}

.think-header .rotate {
  transform: rotate(180deg);
}

.think-expanded {
  color: #409eff;
}

/* ===== 其他调整 ===== */
.loading-indicator {
  color: #909399;
  font-size: 14px;
}

/* 调整输入框高度 */
.message-input {
  ::v-deep .el-textarea__inner {
    min-height: 60px !important;
    max-height: 120px !important;
    padding-right: 100px;
  }
}
</style>